unit MultiplayerPlayer;

interface

uses
  System.Net, System.Web, System.XML, Settings, System.Windows.Forms;

type
  TMultiplayerPlayer = class
  private
    _name : String;
    _id : Integer;
    _guid : String;
    _canUpdate : Boolean;
    
  public
    property Name : String read _name write _name;
    property Id : Integer read _id write _id;
    property Uid : String read _guid;
    
    constructor Create(name : String); Overload;
    constructor Create(name : String; id : Integer); Overload;

    function ToString() : String; override;
    procedure Update();
  end;

implementation

constructor TMultiplayerPlayer.Create(name : String);
begin
  inherited Create;

  self.Name := name;
  self._guid := Guid.NewGuid().ToString();
  self._canUpdate := true;
end;

constructor TMultiplayerPlayer.Create(name: string; id: Integer);
begin
  inherited Create;
  
  self.Name := name;
  self._id := id;
  self._canUpdate := false;  
end;

procedure TMultiplayerPlayer.Update();
var
  request : WebClient;
  response : String;
  xdoc : XmlDocument;
  keyNode : XmlNode;
  requests : XmlNodeList;
  i: Integer;
  requestNode : XmlNode;
  
begin
  if (self._canUpdate) then
  begin
    request := WebClient.Create();
    response := request.DownloadData(TSettings.MultiplayerUrl + '?action=updatePlayer&guid=' + self._guid + '&name=' + self.Name);

    xdoc := XmlDocument.Create();
    xdoc.LoadXml(response);

    keyNode := xdoc.GetElementsByTagName('key')[0];
    self._id := Int32.Parse(keyNode.FirstChild.Value);

    requests := xdoc.GetElementsByTagName('request');
    for i := 0 to requests.Count - 1 do
    begin
      requestNode := requests[i];
      MessageBox.Show(System.String.Format('You have been challenged by {0}', requestNode.Attributes['name'].Value));
    end;

    request.Dispose();
  end;
end;

function TMultiplayerPlayer.ToString() : String;
begin
  result := self.Name;
end;

end.
